<template>
  <div class="list">
    <div class="filter-container">
      <el-input
        v-model="bookLists.title"
        type="text"
        placeholder="书名"
        :clearable="true"
        class="filter-item"
        @input="inputHandler"
      />
      <el-input
        v-model="bookLists.author"
        class="filter-item"
        type="text"
        placeholder="作者"
        :clearable="true"
        :maxlength="300"
        @input="inputHandler"
      />
      <el-select
        v-model="bookLists.category"
        class="filter-item"
        placeholder="分类"
        :clearable="true"
        @change="changeHandler"
      >
        <el-option v-for="item in categoryList" :key="item.index" :value="item.categoryText">{{ item.categoryText+'('+item.num+')' }}</el-option>
      </el-select>
      <el-button v-waves type="primary" class="list-button" @click="debounceHandleValuesChange()">查询</el-button>
      <el-button type="primary" class="list-button" @click="addBook">新增</el-button>
      <el-checkbox v-model="checked" class="list-checkbox">显示封面</el-checkbox>
    </div>
    <el-table
      v-loading="loading"
      :data="bookList"
      fit
      highlight-current-row
      style="text-align: center; width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column
        label="ID"
        width="80"
        prop="id"
        align="center"
        sortable="custom"
      >
        <template v-slot="{row:{ id }}">
          <span>{{ id }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="书名"
        width="180"
        prop="title"
        align="center"
      >
        <template v-slot="{row:{ title }}">
          <span v-html="title" />
        </template>
      </el-table-column>
      <el-table-column
        label="作者"
        width="120"
        prop="author"
        align="center"
      >
        <template v-slot="{row:{ author }}">
          <span v-html="author" />
        </template>
      </el-table-column>
      <el-table-column
        label="出版社"
        width="150"
        prop="publisher"
        align="center"
      />
      <el-table-column
        label="分类"
        width="120"
        prop="categoryText"
        align="center"
      />
      <el-table-column
        label="语言"
        width="60"
        prop="language"
        align="center"
      />
      <el-table-column
        v-if="checked"
        label="封面"
        width="150"
        prop="cover"
        align="center"
      >
        <template v-slot="{row:{ cover}}">
          <a :href="cover" target="_blank">
            <img :src="cover" alt="..." style="width: 120px; height: 150px;">
          </a>
        </template>
      </el-table-column>
      <el-table-column
        label="文件名"
        width="150"
        prop="originalName"
        align="center"
      >
        <template v-slot="scope">
          <span>
            {{ scope.row.originalName | filterValue }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="文件路径"
        width="120"
        prop="filePath"
        align="center"
      >
        <template v-slot="scope">
          <span>
            {{ scope.row.filePath | filterValue }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="图片路径"
        width="120"
        prop="coverPath"
        align="center"
      >
        <template v-slot="scope">
          <span>
            {{ scope.row.coverPath | filterValue }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="解压路径"
        width="120"
        prop="unzipPath"
        align="center"
      >
        <template v-slot="scope">
          <span>
            {{ scope.row.unzipPath | filterValue }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="上传人"
        width="90"
        prop="createUser"
        align="center"
      >
        <template v-slot="scope">
          <span>
            {{ scope.row.createUser | filterValue }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="上传时间"
        width="100"
        prop="createDt"
        align="center"
      >
        <template v-slot="scope">
          <span>{{ scope.row.createDt | filterTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="120"
        align="center"
        fixed="right"
      >
        <template v-slot="scope">
          <el-button type="primary" size="mini" :loading="false" icon="el-icon-delete" @click="delBook(scope)" />
          <el-button type="primary" size="mini" :loading="false" icon="el-icon-edit" @click="editBook(scope)" />
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :hidden="!total"
      :total="total"
      :page="getPageSize.page"
      :limit="getPageSize.pageSize"
      @pagination="changePagination"
    />
  </div>
</template>

<script>
import pagination from './../../components/Pagination'
import { getCategory, getBookList, deleteBook } from './../../api/book'
import waves from '../../directive/waves/waves'
import debounce from './../../utils/debounce'
import moment from 'moment'

export default {
  name: 'List',
  components: {
    pagination
  },
  directives: {
    waves
  },
  filters: {
    filterTime: function(value) {
      return value ? moment(value).format('YYYY/MM/DD hh:mm') : '无'
    },
    filterValue: function(value) {
      if (value) {
        return value
      } else {
        return '无'
      }
    }
  },
  data() {
    return {
      bookLists: {
        title: '',
        author: '',
        category: ''
      },
      sort: null,
      loading: false,
      categoryList: [],
      bookList: [],
      checked: false,
      getBookQuery: {},
      getPageSize: {},
      total: 0,
      debounceHandleValuesChange: undefined,
      debounceHandleInput: undefined
    }
  },
  created() {
    this.init()
    this.debounceHandleValuesChange = debounce(this.checkBook, 200, false)
    this.debounceHandleInput = debounce(this.initBookList, 500, false)
  },
  mounted() {
    this.initCategory()
    this.initBookList()
  },
  methods: {
    init() {
      const defaultPageSize = {
        pageSize: 10,
        page: 1
      }
      this.getPageSize = { ...defaultPageSize, ...this.getPageSize }
    },
    getQuery() {
      const query = { ...this.getPageSize }
      for (const item in this.bookLists) {
        if (this.bookLists[item]) {
          query[item] = this.bookLists[item]
        }
      }
      if (this.sort) {
        query['sort'] = this.sort
      }
      return query
    },
    highLight(item, temp) {
      const value = item.replace(new RegExp(`${temp}`, 'ig'), `<span style="color: pink">${temp}</span>`)
      return value
    },
    initBookList() {
      const query = this.getQuery()
      this.loading = true
      getBookList(query).then(res => {
        this.bookList = []
        if (res.data.bookList.length > 0) {
          this.total = res.data.count
          res.data.bookList.forEach(item => {
            if (query.title) {
              item.title = this.highLight(item.title, query.title)
            }
            if (query.author) {
              item.author = this.highLight(item.author, query.author)
            }
            this.bookList.push(item)
          })
        } else {
          this.total = 0
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    initCategory() {
      getCategory().then(res => {
        this.categoryList = []
        res.data.categoryList.forEach(item => {
          this.categoryList.push(item)
        })
      }).catch(() => {
        return 0
      })
    },
    inputHandler() {
      this.debounceHandleInput()
    },
    changeHandler(value) {
      this.initBookList()
    },
    checkBook() {
      this.initBookList()
    },
    addBook() {
      this.$router.push('/book/upload')
    },
    sortChange({ prop, order }) {
      this.sort = order === 'ascending' ? `+${prop}` : `-${prop}`
      this.initBookList()
    },
    delBook(scope) {
      deleteBook({ book: scope.row }).then(res => {
        this.$message({
          type: 'success',
          message: '删除成功'
        })
        this.initBookList()
      }).catch(() => {
        // console.log(err)
      })
    },
    editBook(scope) {
      if (!Number(scope.row.updateType)) {
        this.$notify({
          type: 'warning',
          message: '内置图书不能编辑',
          title: '提醒',
          duration: 2000
        })
      } else {
        this.$router.push(`/book/edit/${scope.row.fileName}`)
      }
    },
    changePagination({ page, limit }) {
      this.getPageSize = Object.assign({}, this.getPageSize, { page, pageSize: limit })
      this.initBookList()
    }
  }
}
</script>

<style lang="scss" scoped>
$width250: 250px;

@mixin fontStyle{
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
.list{
  padding: 0 10px 20px;
  .filter-container{
    padding: 10px 10px;
    .filter-item{
      width: $width250;
      margin-right: 30px;
      @include fontStyle;
    }
    .list-button{
      margin-right: 10px;
      margin-bottom: 10px;
      vertical-align: middle;
    }
    .list-checkbox{
      @extend .list-button;
      margin-left: 20px;
    }
  }
}
</style>
